<?php 
/////////////////////////////////////////////////////////////////////////////
// 
//
// workflow_system
//
// workflow_copyright
// 
/////////////////////////////////////////////////////////////////////////////

/**
 * FILE_NAME : order.class.php   FILE_PATH : \\classes\application\order.class.php
 * ....商品订单管理
 *
 * @copyright workflow_system 
 * @author workflow Develop Team 
 * @package 
 * @subpackage 
 * @version Wed Aug 22 14:37:46 CST 2007
 */

defined('Base_Use_Sign') or die("this is invalid system!please contact <a href='http://www.shopnc.net'>www.shopnc.net</>.");
class ProductOrderClass extends FrameWork {
	/**
	 * 商品对象
	 *
	 * @var obj
	 */
	var $obj_product;
	
	/**
	 * 取得订单列表
	 *
	 * @param array $obj_condition
	 * @param object $obj_page
	 * @return array $product_order_array
	 */
	function getProductOrderList($obj_condition, &$obj_page,$fields="*",$type='simple'){
		/**
		 * 构造查询条件
		 */
		$condition_str = $this->_conditionSearch($obj_condition);
		if ($type == 'simple'){
			$product_order_array = $GLOBALS['db']->GetList($condition_str, $obj_page, "product_sold",$fields);
		}else if ($type == 'more'){
			if ($obj_condition['buyer_name'] != ''){
				$join_where = array("product_sold.buyer_id=shop_info.member_id",'product_sold.seller_id=member.member_id');
			}else {
				$join_where = array("product_sold.seller_id=shop_info.member_id",'product_sold.seller_id=member.member_id');
			}
			$product_order_array = $GLOBALS['db']->GetJoinList($obj_page,array('product_sold','shop_info','member'),"left join",$join_where,array('*','shop_name','login_name'),$condition_str);
		}
		
		//member,shopinfo
		return $product_order_array;
	}
	/**
	 * 更新商品订单状态
	 *
	 * @param array $input
	 * @return boolean
	 */
	function updateProductOrderState($input){
		$valueArray = array();
		$valueArray["sp_state"]	= $input["txtSPstate"];
		if ($input["alipay_id"] != ''){
			$valueArray["alipay_id"] = $input["alipay_id"];
		}
		if ($input['deliver_time'] != ''){
			$valueArray['deliver_time'] = $input['deliver_time'];
		}
		if ($input['receive_time'] != ''){
			$valueArray['receive_time'] = $input['receive_time'];
		}
		if ($input['pay_time'] != ''){
			$valueArray['pay_time'] = $input['pay_time'];
		}
		$valueArray['is_complaint'] = intval($input['is_complaint']) ? intval($input['is_complaint']) : 0;
		$update_rs = $GLOBALS['db']->UpdateRow($input["spcode"], $valueArray, 'product_sold', 'sp_code');
		return $update_rs;
	}

	/**
	 * 获得商品订单最大ID
	 *
	 * @return int $product_order_last_id
	 */
	function getProductOrderLastId(){
		$product_order_row = $GLOBALS['db']->GetLastRow('product_sold','sp_id','');
		$product_order_last_id = $product_order_row['sp_id'];
		return $product_order_last_id;
	}

	/**
	 * 保存商品购买订单
	 *
	 * @param array $input
	 * @return boolean
	 */
	function saveProductOrder($input){
		//初始化变量
		$this->_getConfiginfo();
		//加载语言包
		$this->getlang("own_order");
		$_GET['action'] = 'view';
		$_GET['sp_html'] = '1';
		$_GET['pid'] = $input['txtPcode'];
		ob_start();
		require_once('../home/product.php');
		$html_content = ob_get_contents();
		ob_end_clean();
		//取商品页面内容生成快照
		//$html_content = Common::getUrlContent($this->_configinfo['websit']['site_url'].'/home/product.php?action=view&sp_html=1&pid='.$input['txtPcode']);
		//进行正则替换
		//替换购买按钮
		switch($this->_configinfo['websit']['templatesname']){
			case 'default':
				$pattern = '/<div.?class=\"big\".?id=\"button_doBid\"><\/div>/is';
				break;
			case 'orange':
				$pattern = '/<div.?class=\"buybtn\".?id=\"button_doBid\"><\/div>/is';
				break;
			case 'green':
				$pattern = '/<div.?class=\"buybtn\"><\/div>/is';
				break;
		}
		
		$replacement = '<span style="background-color:#CCCCCC"><font color="#0000CC">';
		$replacement .= $this->_lang['langOHtmlRemarkOne'].date('Y').$this->_lang['langOHtmlYear'];
		$replacement .= date('m').$this->_lang['langOHtmlMonth'].date('d').$this->_lang['langOHtmlDay'];
		$replacement .= date('H').$this->_lang['langOHtmlHour'].date('i').$this->_lang['langOHtmlMinute'];
		$replacement .= date('s').$this->_lang['langOHtmlSecond'].$this->_lang['langOHtmlRemarkTwo'];
		$replacement .= '<a target="_blank" href="'.$this->_configinfo['websit']['site_url'].'/home/product.php?action=view&pid='.$input['txtPcode'].'">'.$this->_lang['langOHtmlRemarkThree'].'</a></font></span>';
		$html_content = @preg_replace($pattern,$replacement,$html_content);
		
		//替换清空剩余时间
		/*$pattern = '/<span.?id=\"sp_html_lefttime\".*?id=\"leftTime1\".*?<\/span>/is';
		$html_content = @preg_replace($pattern,'',$html_content);
		//替换清空商品数量
		$pattern = '/<span.?id=\"sp_html_storage\".*?id=\"html_p_storage\".*?<\/span>/is';
		$html_content = @preg_replace($pattern,'',$html_content);*/
		
		if (!get_magic_quotes_gpc()){
			$input['txtPHtml'] = addslashes($html_content);
		}
		//入库
		$valueArray = array();
		$valueArray["sp_code"]		= $input["txtSPcode"];
		$valueArray["seller_id"]	= $input["txtSellerId"];
		$valueArray["buyer_id"]		= $input["txtBuyerId"];
		$valueArray["p_name"]		= $input["txtPname"];
		$valueArray["p_code"]		= $input["txtPcode"];
		$valueArray["pc_id"]		= $input["txtPcid"];
		$valueArray["unit_price"]	= $input["txtUnitPrice"];
		$valueArray["buy_num"]		= $input["txtBuyNum"];
		if ($input["txtTfType"] != ''){
			$valueArray["tf_type"]		= $input["txtTfType"];
		}
		$valueArray["tf_fee"]		= $input["txtTfFee"];
		$valueArray["sell_type"]	= $input["sell_type"];
		$valueArray["total_price"]	= $valueArray["unit_price"]*$valueArray["buy_num"]+$valueArray["tf_fee"];
		$valueArray["receive_code"]	= $input["txtReceiveId"];
		if ($input["photo_url"] != ''){
			$valueArray["p_pic"]		= $input["photo_url"];
		}
		$valueArray["sp_html"]		= $input["txtPHtml"];
		$valueArray["sp_state"]		= $input["sp_state"];
		$valueArray["sold_time"]	= time();
		if ($input['anonymous'] != ''){
			$valueArray["anonymous"]= $input['anonymous'];
		}
		if ($input['txtPayment'] != ''){
			$valueArray["sp_pay_mechod"]= $input["txtPayment"];
		}
		if ($input['sp_currency_category'] != ''){
			$valueArray["sp_currency_category"]= $input["sp_currency_category"];
		}
		if ($input['leaveword'] != ''){
			$valueArray["leaveword"]= $input["leaveword"];
		}
		$insert_rs = $GLOBALS['db']->InsertRow($valueArray, 'product_sold', 'sp_id');
		return $insert_rs;
	}
	
	/**
	 * 更新订单信息
	 * @author workflow Develop Team     
	 * @param  $input 订单参数
	 * @return bool
	 */
	function updateProductOrder($input){
		if (is_array($input)){
			$value_array = array();
			foreach ($input as $k => $v){
				if ($v != ''){
					$value_array[$k] = $v;
				}
			}
			$update_rs = $GLOBALS['db']->UpdateRow($value_array["sp_code"], $value_array, 'product_sold', 'sp_code');
		}
		return $update_rs;
	}
	
	/**
	 * 构造商品检索条件
	 *
	 * @param object $obj_condition 查询条件对象
	 * @return string $conditionStr 返回查询条件SQL字符串
	 */
	function _conditionSearch($obj_condition){
		$conditionStr = "";
		
		/*按照订单编号*/
		if($obj_condition['sp_code'] != ''){
			$conditionStr .= " and product_sold.sp_code = '" . $obj_condition['sp_code'] . "'";
		}
		/*搜索订单类型*/
		if($obj_condition['order_case'] == "sold"){
			$conditionStr .= " and product_sold.seller_id = '" . $obj_condition['member_id'] . "'";
		}elseif ($obj_condition['order_case'] == "bought"){
			$conditionStr .= " and product_sold.buyer_id = '" . $obj_condition['member_id'] . "'";
		}
		/*搜索卖家*/
		if($obj_condition['seller_id'] != ''){
			$conditionStr .= " and product_sold.seller_id = '" . $obj_condition['seller_id'] . "'";
		}
		/*搜索买家*/
		if($obj_condition['buyer_id'] != ''){
			$conditionStr .= " and product_sold.buyer_id = '" . $obj_condition['buyer_id'] . "'";
		}
		/*按照售出时间段搜索*/
		if($obj_condition['search_time'] != ''){
			$conditionStr .= " and product_sold.sold_time > '" . $obj_condition['start_time'] . "' and product_sold.sold_time < '" . $obj_condition['end_time'] . "'";
		}
		/*按商品编号搜索*/
		if($obj_condition['p_code'] != ''){
			$conditionStr .= " and product_sold.p_code = '" . $obj_condition['p_code'] . "'";
		}
		/*按商品名称搜索*/
		if($obj_condition['p_name'] != ''){
			$conditionStr .= " and product_sold.p_name like '%" . $obj_condition['p_name'] . "%'";
		}
		/*订单交易类型*/
		if($obj_condition['sell_type'] != ''){
			$conditionStr .= " and product_sold.sell_type = '" . $obj_condition['sell_type'] . "'";
		}
		/*按订单状态搜索*/
		if($obj_condition['state'] != ''){
			if(is_array($obj_condition['state'])){
				$conditionStr .= " and";
				$condition_or_str = "";
				foreach($obj_condition['state'] as $value){
					$condition_or_str .= " or product_sold.sp_state = '" . $value . "'";
				}
				$conditionStr .= " (" . substr($condition_or_str,3) . ")";
			}else{
				$conditionStr .= " and product_sold.sp_state = '" . $obj_condition['state'] . "'";
			}
		}
		/*按好评状态搜索*/
		if ($obj_condition['comment'] == '0' && $obj_condition['comment'] != ''){/*卖家已好评*/
			$conditionStr .= " and product_sold.sole_have_comment = '1' ";
		}elseif ($obj_condition['comment'] == '1'){/*买家已好评*/
			$conditionStr .= " and product_sold.buy_have_comment = '1' ";
		}elseif ($obj_condition['comment'] == '2'){/*双方已好评*/
			$conditionStr .= " and product_sold.buy_have_comment = '1' and sole_have_comment = '1' ";
		}elseif ($obj_condition['comment'] == '3'){/*双方未好评*/
			$conditionStr .= " and product_sold.buy_have_comment = '0' and sole_have_comment = '0' ";
		}elseif ($obj_condition['comment'] == '4'){/*卖家未好评*/
			$conditionStr .= " and product_sold.sole_have_comment = '0' ";
		}elseif ($obj_condition['comment'] == '5'){/*买家未好评*/
			$conditionStr .= " and product_sold.buy_have_comment = '0' ";
		}
		
		/*删除状态0为正常1为删除*/
		if($obj_condition['del'] == 1){
			$conditionStr .= " and product_sold.sp_del='1' ";
		}else{
			$conditionStr .= " and product_sold.sp_del='0'";
		}
		
		/*按时间搜索6个月*/
		if ($obj_condition['time'] != 'no'){
			if ($obj_condition['time'] == 1){/*6个月之前的*/
				$time = time()-180*24*60*60;
				$conditionStr .= " and product_sold.sold_time < '" . $time . "' ";
			}else if ($obj_condition['time'] == 2) {/*最近一个月的*/
				$time = time()-30*24*60*60;
				$conditionStr .= " and product_sold.sold_time > '" . $time . "' ";
			}else if ($obj_condition['time'] == 3) {/*6个月之后*/
				$time = time()-180*24*60*60;
				$conditionStr .= " and product_sold.sold_time > '" . $time . "' ";
			}
		}
		
		//支付方式
		if ($obj_condition['sp_pay_mechod'] != ''){
			$conditionStr .= " and product_sold.sp_pay_mechod = '" . $obj_condition['sp_pay_mechod'] . "' ";
		}
		
		//商铺名
		if ($obj_condition['shop_name'] != ''){
			$conditionStr .= " and shop_info.shop_name like '%" . $obj_condition['shop_name'] . "%' ";
		}
		//卖家名
		if ($obj_condition['seller_name'] != ''){
			$conditionStr .= " and member.login_name like '%" . $obj_condition['seller_name'] . "%' ";
		}
		//买家名
		if ($obj_condition['buyer_name'] != ''){
			$conditionStr .= " and member.login_name like '%" . $obj_condition['buyer_name'] . "%' ";
		}
		
		//分组排序
		if ($obj_condition['group_by'] != ''){
			$conditionStr .= " group by product_sold.".$obj_condition['group_by'];
		}
		
		
		/*列表排序方式*/
		if ($obj_condition['order'] != 'no'){
			if($obj_condition['order'] == 1){
				$conditionStr .= " order by product_sold.sold_time desc";
			}else{
				if ($obj_condition['order'] != ''){
					$conditionStr .= " order by ".$obj_condition['order'];
				}else {
					$conditionStr .= " order by product_sold.sold_time";
				}
				
			}
		}
		return $conditionStr;
	}

	/**
	 * 得到某个售出商品记录
	 *
	 * @param int $orderid
	 * @return var[]
	 */
	function getOneOrder($orderid){
		if (intval($orderid) > 0){
			$order_row = $GLOBALS['db']->GetOneRow(intval($orderid),'product_sold','sp_id');
		}
		return $order_row;
	}
	
	/**
	 * 得到某个售出商品记录 by sp_code
	 *
	 * @param int $orderid
	 * @return var[]
	 */
	function getOneOrderBySpcode($orderid){
		if ($orderid != ''){
			$order_row = $GLOBALS['db']->GetOneRow($orderid,'product_sold','sp_code');
		}
		return $order_row;
	}
	
	/**
	 * 更新商品订单的评价状态
	 *
	 * @param string $genre 更新的评价类型，B买家评价，S卖家评价
	 * @param int $orderid 订单ID
	 * @return boolean
	 */
	function updateProductOrderCommentState($orderid,$genre = "b"){
		//echo $orderid;
		$valueArray = array();
		if ($genre == "s"){
			$valueArray["buy_have_comment"] = 1;
		}else if($genre == "b"){
			$valueArray["sole_have_comment"]	= 1;
		}
		$update_rs = $GLOBALS['db']->UpdateRow($orderid, $valueArray, 'product_sold', 'sp_id');
		return $update_rs;
	}
	/**
	 * 更新到期团购商品订单状态
	 * 从团购中——》团购失败
	 * @param unknown_type $input
	 * @return unknown
	 */
	function updateProductOrderInCondition(){

		if (!is_object($this->obj_product)){
			require_once("product.class.php");
			$this->obj_product = new ProductClass();
		}
		//过期的团购商品
		$obj_tobe_end_condition['state'] = '1';
		$obj_tobe_end_condition['now_end'] = 'now';//超过结束时间
		$obj_tobe_end_condition['sell_type'] = '2';//团购
		$product_tobe_end_rs = $this->obj_product->getProductList($obj_tobe_end_condition, $obj_tobe_end_page);
		if(is_array($product_tobe_end_rs)){
			foreach ($product_tobe_end_rs as $key=>$value){
				$update_state_condition["p_code"][$key] = $value['p_code'];
				//将到期的团购商品，列表商品的都是数量不够到期的，所以将卖出的商品数量重新加到商品库存中
				$value_array = array();
				$value_array['p_storage'] = $value['p_sold_num']+$value['p_storage'];
				$value_array['p_sold_num'] = 0;
				$value_array['p_sold_sum'] = abs($value['p_sold_sum']-$value['p_sold_num']);
				$GLOBALS['db']->UpdateRow($value["p_code"], $value_array, 'product', 'p_code');
				unset($value_array);
			}
		}
		
		//更新订单状态
		$update_array["sp_state"] = "5";
		$input["sp_old_state"] = "4";
		
		if(count($update_state_condition["p_code"]) > 0){
			if(is_array($update_state_condition["p_code"])){
				foreach($update_state_condition["p_code"] as $value){
					$condition_or_str .= " or p_code = '" . $value . "'";
				}
				$condition = " (" . substr($condition_or_str,3) . ")";
			}else{
				$condition = " p_code = '" . $update_state_condition["p_code"] . "'";
			}

			if("" != $input["sp_old_state"]){
				$condition .= " and sp_state = '" . $input["sp_old_state"] . "'";
			}
			$update_rs = $GLOBALS['db']->UpdateRows('product_sold', $update_array, $condition);
			
			//判断如果是预存款支付的话，则将金额打回到预存款账户上
			if ($update_rs === true){
				//取订单预存款支付的内容
				//语言包
				$this->getlang('own_predeposit');
				unset($condition);
				foreach($update_state_condition["p_code"] as $value){
					$condition['p_code'] = $value;
					$condition['sp_pay_mechod'] = 'predeposit';
					$condition['state'] = '5';
					$condition['sell_type'] = '2';
					$order_array = $this->getProductOrderList($condition,$page);
					if (!empty($order_array)){
						//团购失败退款
						require_once ("predeposit.class.php");
						$obj_predeposit = new PredepositClass ( );
						require_once("member.class.php");
						$obj_member = new MemberClass();
						foreach ($order_array as $k => $v) {
							//买家
							$value_array = array ();
							$value_array ['predeposit_type'] = '6'; //团购失败退款
							$value_array ['predeposit_state'] = '1';
							$value_array ['member_id'] = $v['buyer_id'];
							$value_array ['sp_code'] = $v["sp_code"];
							$value_array ['available_amount'] = '+' . $v['total_price'];
							$value_array ['system_remark'] = $this->_lang['langPreDetailTypeSix'];
							$value_array ['create_time'] = time ();
							$value_array ['update_time'] = time ();
							$value_array ['payment'] = 'predeposit';
							$obj_predeposit->addPredepositDetail ( $value_array );
							unset ( $value_array );
							//对买家帐号进行操作
							$value_array = array ();
							$value_array ['available_predeposit'] = '+' . $v['total_price'];
							$obj_member->modifyMember ( $value_array, $v['buyer_id'], 'predeposit' );
							unset ( $value_array );
						}
						unset($obj_predeposit,$obj_member);
					}
					unset($order_array);
				}
			}
		}
		return $update_rs;
	}
	/**
	 * 删除订单（逻辑删除）
	 *
	 * @param array $input
	 * @return boolean
	 */
	function updateProductDelState($input){
		$valueArray = array();
		$valueArray["sp_del"]	= $input["txtDel"];
		if (is_array($input["chboxSPid"])){
			foreach ($input["chboxSPid"] as $value){
				$update_rs = $GLOBALS['db']->UpdateRow($value, $valueArray, 'product_sold', 'sp_id');
			}
		}else {
			$update_rs = $GLOBALS['db']->UpdateRow($input["chboxSPid"], $valueArray, 'product_sold', 'sp_id');
		}
		return $update_rs;
	}
	/**
	 * 当超过40天时，自动评价
	 * @author workflow Develop Team
	 * @param   
	 * @return bool
	 */
	function orderAutoComment(){
		$time = time()+40*24*60*60;
		$condition = "and sold_time > '" . $time . "' and sp_del='0' and sole_have_comment = '0' and buy_have_comment = '0' ";
		$array = $GLOBALS['db']->GetList($condition,&$obj_page,'product_sold');
		/**
		 * 如果超过40天了，自动把评价状态变为已评，会员表中信用度+1
		 */
		if (is_array($array)){
			if (!is_object($obj_member)) {
				require_once("member.class.php");
				$obj_member = new MemberClass();
			}
			foreach ($array as $value){
				/*更新订单状态*/
				$valueArray = array();
				$valueArray['sole_have_comment'] = 1;
				$valueArray['buy_have_comment'] = 1;
				$result = $GLOBALS['db']->UpdateRow($value["sp_id"], $valueArray, 'product_sold', 'sp_id');
				if ($result !== true){
					return  false;
				}
				/*更新会员表状态*/
				$valueArray = array();
				$valueArray['sale_score'] = 'sale_score+1';
				$result = $GLOBALS['db']->UpdateRow($value["seller_id"], $valueArray, 'member_extend', 'member_id',true);
				if ($result !== true){
					return  false;
				}
				$valueArray = array();
				$valueArray['buy_score'] = 'buy_score+1';
				$result = $GLOBALS['db']->UpdateRow($value["buyer_id"], $valueArray, 'member_extend', 'member_id',true);
				if ($result !== true){
					return  false;
				}
				unset($valueArray);
			}			
		}
		unset($array);
		return true;
	}
	/**
	 * 交易统计
	 *
	 * @param string $condition
	 * @param int $row_nums
	 * @return array
	 */
	function getStaticsTrade($condition, $row_nums){
		$condition = $this->_conditionSearch($condition);
		
		$statics_array = $GLOBALS['db']->GetList($condition,$page,'product_sold','count(*) as num, p_name',$row_nums,'',' p_name');

		return $statics_array;
	}
	
	/**
	 * 取发货单信息
	 * @author workflow Develop Team    
	 * @param  $order_code 订单号
	 * @return array
	 */
	function getInvoice($order_code){
		if ($order_code != ''){
			$result = $GLOBALS['db']->GetOneRow($order_code,'invoice','order_code');
			return $result;
		}
		return false;
	}
	
	/**
	 * 新增发货单
	 * @author workflow Develop Team    
	 * @param  $param_array 发货单参数
	 * @return bool
	 */
	function addInvoice($param_array){
		if (is_array($param_array)){
			$value_array = array();
			foreach ($param_array as $k => $v){
				if ($v !== ''){
					$value_array[$k] = $v;
				}
			}
			$insert_rs = $GLOBALS['db']->InsertRow($value_array, 'invoice', 'invoice_id');
			return $insert_rs;
		}else {
			return false;
		}
		
	}
	
	/**
	 * 更新指定团购商品的订单状态
	 * @author workflow Develop Team     
	 * @param  $p_code 商品编号
	 * @return bool
	 */
	function updateProductOrderByGroup($p_code){
		if ($p_code != ''){
			$update_array = array();
			$update_array['sp_state'] = '0';
			$condition .= " p_code = '" . $p_code . "' and sp_state='4'";
			$update_rs = $GLOBALS['db']->UpdateRows('product_sold', $update_array, $condition);
			return $update_rs;
		}else {
			return false;
		}
	}
	
	/**
	 * 关闭到期的交易 默认为7天
	 * @author workflow Develop Team     
	 * @param  $day 天数,默认为7天
	 * @return bool
	 */
	function closeProductOrderByTime($day='7'){
		$update_array = array();
		$update_array['sp_state'] = '7';
		$time = time()-$day*24*60*60;
		$condition = " sp_state = '0' and sold_time < ".$time;
		$update_rs = $GLOBALS['db']->UpdateRows('product_sold', $update_array, $condition);
		return true;
	}
}
?>